package ua.com.myjava.francais;

import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.mongo.MongoClient;

public class ImageService {
    private MongoClient mongo;

    public ImageService(MongoClient mongo) {
        this.mongo = mongo;
    }

    public void listImages(Message<JsonObject> msg) {
        // issue a find command to mongo to fetch all documents from the "images" collection.
        mongo.find("images", msg.body(), lookup -> {
            // error handling
            if (lookup.failed()) {
                msg.fail(500, lookup.cause().getMessage());
                return;
            }

            // now convert the list to a JsonArray because it will be easier to encode the final object as the response.
            final JsonArray json = new JsonArray();

            for (JsonObject o : lookup.result()) {
                json.add(o);
            }

            msg.reply(json);
        });

    }

    public void nextImage(Message<JsonObject> msg) {
        mongo.save("images-answers", msg.body(), save -> {
            // error handling
            if (save.failed()) {
                msg.fail(500, save.cause().getMessage());
                return;
            }

            msg.reply(new JsonObject());
        });
    }

    public void addImage(Message<JsonObject> msg) {
        mongo.insert("images", msg.body(), res -> {
            System.out.println("inserted " + msg.body().encode());
            msg.reply(new JsonObject());
        });
    }
}
